﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraScheduler;
using DevExpress.XtraScheduler.UI;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraTab;
using DevExpress.XtraEditors;

namespace BuildHelper.Scheduler
{
    public partial class ActionAppointmentForm :DevExpress.XtraScheduler.UI.AppointmentForm
    {
        
        public ActionAppointmentForm()
        {
            InitializeComponent();
        }
        
        Appointment app;
        
        public ActionAppointmentForm(SchedulerControl control, Appointment apt)
            : base(control, apt)
        {
            InitializeComponent();
            Init(apt);
        }
        
        public ActionAppointmentForm(SchedulerControl control, Appointment apt, bool openRecurrenceForm)
            : base(control, apt, openRecurrenceForm)
        {
            InitializeComponent();
            Init(apt);
        }
        
        private void Init(Appointment apt)
        {
            app = apt;
            PrepareControls();
            foreach (XtraTabPage p in xtraTabControl1.TabPages)
            {
                p.PageVisible = false;
                foreach (Control c in p.Controls)
                {
                    if (c is BaseEdit)
                    {
                        (c as BaseEdit).EditValueChanged += new EventHandler(this.Param_Changed);
                    }
                    else if (c is ZadanieParamsControl)
                    {
                        (c as ZadanieParamsControl).EditValueChanged += new EventHandler(this.Param_Changed);
                        (c as ZadanieParamsControl).InitEvents();
                    }
                }
            }
            Zadanie z = null;

            if (IsNewAppointment)
            {
                DateTime dts = DateTime.Now.AddMinutes(1).AddSeconds(DateTime.Now.Second * -1);
                DateTime dte = DateTime.Now.AddMinutes(31).AddSeconds(DateTime.Now.Second * -1);

                Appointment a = null;
                
                if (apt.Start > dts)
                {
                    dts = apt.Start;
                    dte = app.End;
                }
                if (apt.IsRecurring)
                    a = this.Control.Storage.CreateAppointment(AppointmentType.Pattern);
                else
                    a = this.Control.Storage.CreateAppointment(AppointmentType.Normal);

                a.Start = dts;
                a.End = dte;
                a.LabelId = 1;
                if (apt.IsRecurring)
                {
                    a.RecurrenceInfo.Type = RecurrenceType.Daily;
                    a.RecurrenceInfo.Start = apt.Start;
                    a.RecurrenceInfo.Range = RecurrenceRange.NoEndDate;
                }
                a.HasReminder = true;
                a.Reminder.TimeBeforeStart = new TimeSpan();
                apt.RunMethod("Assign", a);
                if (apt.IsRecurring)
                    controller.ApplyRecurrence(a);

                controller.StartDate = apt.Start;
                controller.EndDate = apt.End;

                controller.StartTime = new TimeSpan(apt.Start.Hour, apt.Start.Minute, apt.Start.Second);
                controller.EndTime = new TimeSpan(apt.End.Hour, apt.End.Minute, apt.End.Second);

                controller.HasReminder = true;
                controller.ReminderTimeBeforeStart = new TimeSpan();
                chkReminder.Checked = true;
                edtLabel.SelectedIndex = 1;
                UpdateReminderCombo();
                
            }
            else
                 z = Zadanie.Zadania[app.CustomFields["WRK_ZAD_ZADANIE"].AsString()];

            if (this.controller != null && this.controller.EditedAppointmentCopy != null && lueZadanie != null)
            {
                lueZadanie.EditValue = this.controller.EditedAppointmentCopy.CustomFields["WRK_ZAD_ZADANIE"];
                foreach (XtraTabPage p in xtraTabControl1.TabPages)
                {
                    if (p.Tag.AsString() == lueZadanie.EditValue.AsString())
                    {
                        p.PageVisible = true;
                        break;
                    }
                }
                BaseEdit edit;
                if (z != null)
                {
                    if (z.Parameters != null && xtraTabControl1.SelectedTabPage !=null)
                    {
                        for (int i = 0; i <z.Parameters.Length; i++)
                        {
                            edit = GetEdit(i+1);
                            edit.EditValue = GetParamValue(z, i+1);
                            SetParamValue(edit);
                        }
                    }
                }
            }
            UpdateForm();
           
            this.cbReminder.Visible = false;
            this.chkReminder.Visible = false;
            edtResource.Visible = false;
            lueZadanie.Properties.BeginInit();
            lueZadanie.Properties.DataSource = Zadanie.Zadania;
            lueZadanie.EditValueChanged +=new EventHandler(lueZadanie_EditValueChanged);
            lueZadanie.Properties.EndInit();
            UpdateFormCaption();
        }
        private object GetParamValue(Zadanie z, int no)
        {
            string str = controller.EditedAppointmentCopy.CustomFields["WRK_ZAD_PARAM" + no].AsString();
            return z.ConvertParam(str, no);
        }
        private BaseEdit GetEdit(int no)
        {
            if (xtraTabControl1.SelectedTabPage != null)
            {
                foreach (Control c in xtraTabControl1.SelectedTabPage.Controls)
                {
                    if (c is BaseEdit && c.Tag.AsString() == no.AsString())
                        return c as BaseEdit;
                    else if (c is ZadanieParamsControl)
                        return (c as ZadanieParamsControl).GetEdit(no);
                }
            }
            return null;
        }

        private void PrepareControls()
        {
            //foreach (Zadanie z in Zadanie.Zadania)
            //    if (z.Label != null)
            //        edtLabel.Properties.Items.Add(new ImageComboBoxItem(z.Nazwa, z.Label, -1));
            //edtLabel.Properties.Items[0].Description = "Brak";
        }
        
        AppointmentFormController controller;
        protected override DevExpress.XtraScheduler.UI.AppointmentFormController CreateController(SchedulerControl control, Appointment apt)
        {
            controller = base.CreateController(control, apt);
            return controller;
        }
        protected override void OnOkButton()
        {
            if (lueZadanie.EditValue.IsNull())
            {
                this.ShowDxErrorDialog("Wybierz zadanie");
                return;
            }
            if (xtraTabControl1.SelectedTabPage != null &&
                xtraTabControl1.SelectedTabPage.Controls.Count == 1 &&
                xtraTabControl1.SelectedTabPage.Controls[0] is ZadanieParamsControl)
            {
                if (!(xtraTabControl1.SelectedTabPage.Controls[0] as ZadanieParamsControl).ValidateAll())
                {
                    if ((xtraTabControl1.SelectedTabPage.Controls[0] as ZadanieParamsControl).ErrorMsg.IsNotNull())
                        this.ShowDxErrorDialog((xtraTabControl1.SelectedTabPage.Controls[0] as ZadanieParamsControl).ErrorMsg);
                    else
                        this.ShowDxErrorDialog("Błąd walidacji.");
                    return;
                }
            }
            base.OnOkButton();
        }
        private void lueZadanie_EditValueChanged(object sender, EventArgs e)
        {
            if (this.controller.EditedAppointmentCopy != null)
                this.controller.EditedAppointmentCopy.CustomFields["WRK_ZAD_ZADANIE"] = lueZadanie.EditValue;
            for (int i = 1; i <= Zadanie.MAX_PARAMS; i++)
                this.controller.EditedAppointmentCopy.CustomFields["WRK_ZAD_PARAM" + i] = DBNull.Value;
            
            tbSubject.Text = lueZadanie.Text;
            if (xtraTabControl1.SelectedTabPage != null)
                xtraTabControl1.SelectedTabPage.PageVisible = false;

            foreach (XtraTabPage p in xtraTabControl1.TabPages)
            {
                if (p.Tag.AsString() == lueZadanie.EditValue.AsString())
                {
                    p.Text = lueZadanie.Text;
                    p.PageVisible = true;
                    if (p.Controls.Count == 1 && p.Controls[0] is ZadanieParamsControl)
                    {
                        (p.Controls[0] as ZadanieParamsControl).SetDefault();
                    }
                    break;
                }
            }
            Zadanie z = Zadanie.Zadania[lueZadanie.EditValue.AsString()];
            if (z != null && z.Label != null)
            {
                edtLabel.Label = z.Label;
            }
        }
        private void SetParamValue(object sender)
        {
            BaseEdit edit = sender as BaseEdit;
            if (edit != null)
                this.controller.EditedAppointmentCopy.CustomFields["WRK_ZAD_PARAM" + edit.Tag.AsString()] = edit.EditValue.AsString();
        }

        private void Param_Changed(object sender, EventArgs e)
        {
            SetParamValue(sender);
        }

        protected override void OnRecurrenceButton()
        {
            base.OnRecurrenceButton();
            this.cbReminder.Visible = false;
            this.chkReminder.Visible = false;
            edtResource.Visible = false;
            UpdateFormCaption();
        }
        protected override void UpdateFormCaption()
        {
            string text = "Zadanie: ";
            if (IsNewAppointment)
                text = "Nowe Zadanie: ";
            if (tbSubject.Text.IsNotNull())
                text += tbSubject.Text.AsString();
            else if(lueZadanie != null)
            {
                Zadanie z = Zadanie.Zadania[lueZadanie.EditValue.AsString()];
                if (z != null)
                    text += z.Nazwa;
            }
            if (controller.EditedAppointmentCopy != null && controller.EditedAppointmentCopy.IsRecurring)
                text += " [Cykliczne]";
            this.Text = text;
        }

        private void edtResource_VisibleChanged(object sender, EventArgs e)
        {

        }

    }
}

